package com.ivan.blog.result;

import lombok.Data;

/**
 * 全局统一返回结果类
 */
@Data
public class Result<T> {

    //返回码
    private Integer code;

    //返回消息
    private String message;

    //返回数据
    private T data;

    public Result(){}

    /**
     * @author Ivan
     * @date 2021/4/3 23:18
     * @Description: 构建数据
     */
    public static <T> Result<T> build(T data) {
        Result<T> result = new Result<>();
        if (data != null)
            result.setData(data);
        return result;
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:18
     * @Description: 构建数据 + 结果枚举值
     */
    public static <T> Result<T> build(T data, ResultCodeEnum resultCodeEnum) {
        Result<T> result = build(data);
        result.setCode(resultCodeEnum.getCode());
        result.setMessage(resultCodeEnum.getMessage());
        return result;
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:18
     * @Description: 状态码 + 消息
     */
    public static <T> Result<T> build(Integer code, String message) {
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:15
     * @Description: 操作成功 + 默认200状态码
     */
    public static<T> Result<T> ok(){
        return Result.ok(null);
    }
    public static<T> Result<T> ok(T data){
        return build(data, ResultCodeEnum.SUCCESS);
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:15
     * @Description: 操作失败 + 默认201状态码
     */
    public static<T> Result<T> fail(){
        return Result.fail(null);
    }
    public static<T> Result<T> fail(T data){
        return build(data, ResultCodeEnum.FAIL);
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:15
     * @Description: 设置消息
     */
    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    /**
     * @author Ivan
     * @date 2021/4/3 23:15
     * @Description: 设置状态码
     */
    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }
}
